package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl  implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenTextScan greenTextScan;

    @Override
    public void autoScanNews(Integer id) {
        //查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //从内容中体现纯文本内容和图片
            Map<String,Object> textAndAImages=handleTextAndImages(wmNews);


            //自管理的铭感词过滤
            boolean isSensitive= handleSensitiveScan((String) textAndAImages.get("content"),wmNews);
            //审核文本内容 阿里云接口
            boolean isTextScan=HandleTextScan((String) textAndAImages.get("content"),wmNews);
            if (!isTextScan)return;
            //审核图片 阿里云接口
            boolean isImagesScan=handleImagesScan((List<String>) textAndAImages.get("images"),wmNews);
            if (!isImagesScan)return;
            //4审核成功 //保存app的相关文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
                if (responseResult.getCode().equals(200)){
                    throw new RuntimeException("当前文章中存在违规内容");
                }
                //回填articleid
            wmNews.setArticleId((Long) responseResult.getData());
               updateWmNews(wmNews,(short)9,"success");
        }


    }

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
       boolean isSensitive=true;

        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(sensitiveList);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) {
            updateWmNews(wmNews,(short)2,"违规词汇"+map);
            isSensitive=false;
        }
        return isSensitive;
    }

    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto=new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //文章的频道
        WmChannel wmChannel=wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel==null){
            dto.setChannelName(wmChannel.getName());
        }
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser=wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser!=null){
            dto.setAuthorName(wmUser.getName());
        }
        if (wmNews.getArticleId()!=null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = articleClient.saveArticle(dto);
        return responseResult;
    }

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private Tess4jClient tess4jClient;
    /**
     * 审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        boolean flag=true;
        if (images==null||images.size()==0){
            return flag;
        }
        //下载minio
//        图片去重
          images= images.stream().distinct().collect(Collectors.toList());
          List<byte[]> imageList=new ArrayList<>();
        for (String image : images) {
            byte[] bytes=fileStorageService.downLoadFile(image);
            try {


                    //图片识别文字审核---begin-----

                    //从byte[]转换为butteredImage
                    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                    BufferedImage imageFile = ImageIO.read(in);
                    //识别图片的文字
                    String result = tess4jClient.doOCR(imageFile);

                    //审核是否包含自管理的敏感词
                    boolean isSensitive = handleSensitiveScan(result, wmNews);
                    if(!isSensitive){
                        return isSensitive;
                    }

                    //图片识别文字审核---end-----


                    imageList.add(bytes);


            }catch (Exception e){
                e.printStackTrace();
            }
            imageList.add(bytes);
        }

        //审核图片
        try {
            Map map = greenImageScan.imageScan(imageList);
            if (map != null) {
                if (map.get("suggestion").equals("block")) {
                    flag=false;
                    updateWmNews(wmNews,
                            (short) 2,
                            "当前文章中存在违规内容");
                }


                if (map.get("suggestion").equals("review")) {
                    flag=false;
                    updateWmNews(wmNews,
                            (short) 3,
                            "当前文章中存在违规内容");
                }
            }
        } catch (Exception e) {
            flag=false;
            throw new RuntimeException(e);
        }
        return flag;
    }

    private boolean HandleTextScan(String content, WmNews wmNews) {
        boolean flag=true;
        if ((wmNews.getTitle()+"-"+content)==null)
        {
            return flag;
        }

        try {
            Map map = greenTextScan.greeTextScan((wmNews.getTitle()+"-"+content));
            if (map != null) {
                if (map.get("suggestion").equals("block")) {
                    flag=false;
                    updateWmNews(wmNews,
                            (short) 2,
                            "当前文章中存在违规内容");
                }


                if (map.get("suggestion").equals("review")) {
                    flag=false;
                    updateWmNews(wmNews,
                            (short) 3,
                            "当前文章中存在违规内容");
                }
            }
        } catch (Exception e) {
            flag=false;
            throw new RuntimeException(e);
        }
        return flag;

    }

    private void updateWmNews(WmNews wmNews, Short status ,String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从文章中提取内容和文本图片
     * 提取文章的封面图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {

        //存储图片内容
        StringBuilder stringBuilder=new StringBuilder();
        List<String> images=new ArrayList<>();
     //从文本中提取图片和内容
        if (StringUtils.isNotBlank(wmNews.getContent())){
            List<Map>  maps= JSON.parseArray(wmNews.getContent(),Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("text")){
                stringBuilder.append(map.get("value"));
                }
                if (map.get("type").equals("image")){
                    images.add((String) map.get("value"));
                }

            }
        }
        //        提取文章的封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));

        }
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",images);
        return resultMap;
    }
}
